package com.easyCode.sqlMapper.template;

import com.easyCode.EasyGeneratorAutoConfiguration;
import lombok.SneakyThrows;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.util.ClassUtils;

import java.io.InputStream;
import java.io.Reader;

/**
 * 重写velocity模板引擎加载模板文件的方式,便于加载默认模板文件
 * @author 大忽悠
 * @create 2022/12/18 16:16
 */
public class CustomClassPathResourceLoader extends ClasspathResourceLoader {
    private Class<?> c;

    @SneakyThrows
    @Override
    public Reader getResourceReader(String name, String encoding) throws ResourceNotFoundException {
        Reader result = null;
        InputStream rawStream = null;
        //默认的模板文件通通存放在template目录下面
        if(name.startsWith(SqlTemplateConfig.DEFAULT_TEMPLATE_BASE_DIR)){
            c=EasyGeneratorAutoConfiguration.class;
            rawStream = ClassUtils.getResourceAsStream(c,name);
            if (rawStream != null)
            {
                result = buildReader(rawStream, encoding);
            }
            if (result == null)
            {
                String msg = "ClasspathResourceLoader Error: cannot find resource " + name;

                throw new ResourceNotFoundException( msg, null, rsvc.getLogContext().getStackTrace() );
            }
            return result;
        }
        c=ClasspathResourceLoader.class;
        return super.getResourceReader(name, encoding);
    }
}
